package org.example.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.example.common.result.LeaseException;
import org.example.common.result.ResultCodeEnum;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    //单位毫秒:jwt过期时间
    private static long tokenExpiration = 60 * 60 * 1000L;
    //加密密钥
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToken(Long userId, String username) {
        String token = Jwts.builder().
                //设置分类
                setSubject("USER_INFO").
                //令牌过期时间
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                //jwt负载中的内容,设置用户信息到token
                claim("userId", userId).
                claim("username", username).
                //设置签名,根据签名加密
                signWith(tokenSignKey).
                //压缩变成一行
                compressWith(CompressionCodecs.GZIP).
                compact();
        return token;
    }

    public static Claims parseToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().
                    //设置解密密钥
                    setSigningKey(tokenSignKey).
                    //解析token
                    build().parseClaimsJws(token);
            return claimsJws.getBody();

        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.PARAM_ERROR.getCode(), ResultCodeEnum.TOKEN_EXPIRED.getMessage());
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID.getCode(), ResultCodeEnum.TOKEN_INVALID.getMessage());
        }
    }
}
